<?php
function GetDirName() {
	return implode("", gettimeofday());
}
function CreateDir($dir) {
	while (!is_dir($dir)) {
		   mkdir($dir,0777);
	}
	return $dir;
}
function AutoCreateDir($dir)
{
	for ($i=1; $i<999; $i++) 
	{
		$createDir = $dir."/".sprintf("%03d", $i);
		if (!is_dir($createDir)) {
			   //mkdir($createDir,0777);
				$createDir = sprintf("%03d", $i);
			   break;
		}
		
	}
	return $createDir;
}
function getFileExtension($str) {
	$i = strrpos($str,".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}
function GetUploadFileName($dir, $startName) {
	$arrayFiles = array();
	if (is_dir($dir)) {
	   if ($dh = opendir($dir)) {
			   while (($file = readdir($dh)) !== false) {
				   if ($file != "." && $file != "..") 
						$arrayFiles[count($arrayFiles)] = $file;
			   }
		 }
		 closedir($dh);
	}
	//print_r($arrayFiles);
	$validName = "";
	$exist = false;
	for ($i=65; $i<=90 && !$exist; $i++) {
		$validName = $startName.chr($i);
		$exist = false;
		for ($j=0; $j<count($arrayFiles) && !$exist; $j++) {
			//echo "<br>".$arrayFiles[$j]."-".$validName."<br>";
			if (strpos($arrayFiles[$j], $validName)===false) 
				$exist = false; // not found
			else $exist = true; // found
		}
		if ($exist) $exist = false; // Continue with next value
		else break;
	}
	return $validName;
}

function checkUploadedFile($filename, $fileTypes, &$ext, &$errorMsg)
{
    $errorMsg = "";

	$lastpos = strrpos($filename, '.');

    $ext = substr($filename, $lastpos);

    $lastpos = strrpos($fileTypes, $ext);
    if ($lastpos===false)
    {
        $errorMsg = "Invalid file type, file types must be follow types: $fileTypes";
        return false;
    }
    else return true;
}

function UploadFile($filename, $uploadPath, $fileTypes, &$errorMsg)
{
	$uploadPath = WS_ROOT.$uploadPath;
	
    $errorMsg = $ext = "";
    if (isset($_FILES[$filename]))
    {
        $file = $_FILES[$filename]["tmp_name"];
        if (isset($file) && $file!=null && $file!="")
        {
            if (!checkUploadedFile($_FILES[$filename]["name"], $fileTypes, $ext, $errorMsg))
                return "";    
            $file_name = $_FILES[$filename]["name"];
            $dir = CreateDir($uploadPath);
            $fname = $file_name;
            while (file_exists("$dir/".$fname))
                $fname = rand(100, 999).$file_name;
    
            move_uploaded_file($file, "$dir/".$fname);
        }
        return $fname;
    }
    return "";
}

function DeleteFile($file) 
{
	unlink($file);
}

function UploadFileToDocs($filename, $uploadPath, $fileTypes, &$errorMsg)
{
	global $mainDB, $userSess;
	
	$orgUploadPath = $uploadPath;
	$uploadPath = WS_ROOT.$uploadPath;
    $errorMsg = $ext = "";
	$docID = "";
    if (isset($_FILES[$filename]))
    {
		//echo $uploadPath;
        $file = $_FILES[$filename]["tmp_name"];
		//print_r($_FILES[$filename]);
		//exit;
        if (isset($file) && $file!=null && $file!="")
        {
            if (!checkUploadedFile($_FILES[$filename]["name"], $fileTypes, $ext, $errorMsg))
                return $docID;    
            $dir = CreateDir($uploadPath);
            $fname = genRandomString(20).$ext;
            while (file_exists("$dir/".$fname))
                $fname = genRandomString(20).$ext;
    
			$doc = new docsObj();
			$doc->name = $fname;
			$doc->originalName = $_FILES[$filename]["name"];
			$doc->type	= $_FILES[$filename]["type"];
			$doc->size	= $_FILES[$filename]["size"];
			$doc->uploadedTime	= date("Y-m-d H:i:s");
			if (isset($userSess) && $userSess->id!=null)
				$doc->uploadedBy	= $userSess->id;
			else
				$doc->uploadedBy	= null;
			$doc->uploadedDir	= $orgUploadPath;
			
			if (!docsDAL::Insert($mainDB, $doc, $errorMsg))
			{
				return $docID;
			} else $docID = $doc->id;
		
			move_uploaded_file($file, "$dir/".$fname);
        }
        return $docID;
    }
    return $docID;
}

function DeleteFromDocs($docID)
{
	global $mainDB;
	
	$doc = docsDAL::Load($mainDB, $docID, $errorMsg);
	if ($doc!=null && file_exists(WS_ROOT.$doc->uploadedDir.$doc->name))
	{
		unlink(WS_ROOT.$doc->uploadedDir.$doc->name); 
		
		docsDAL::Pure($mainDB,docsObj::idFieldName()."=".ToSQLPostVAL($docID), $errorMsg);
	}
}

function GetDocSizes($docID)
{
	global $mainDB;

	$doc = docsDAL::Load($mainDB, $docID, $errorPage);
	
	if ($doc!=null && file_exists(WS_ROOT.$doc->uploadedDir.$doc->name))
		return @GetImageSize(WS_ROOT.$doc->uploadedDir.$doc->name); 
	else
		return array(0,0);
}
?>